/*
 * Create:      柿子
 * CreateDate:  2023/10/23
 * Describe：   病区信息设置 - 表单动态添加删除示例 - 注释部分
 * */
import React, { Component } from 'react';
import { Row, Col, Card, Button, Input, Checkbox, Popconfirm, message } from 'antd';
import { Util } from 'tools';
import store from 'store';
import PublicTablePagination from 'pages/common/PubilcTablePagination.jsx';
import DynamicRenderingForm from 'pages/common/DynamicRenderingForm';
import CopyWardInfoConfig from './component/CopyWardInfoConfig';
import iconListVisits from 'assets/images/icon_listvisits.png';
import iconMessages from 'assets/images/icon_messages.png';
import './style/settings.less';

class WardInformationSettings extends Component {
  constructor(props) {
    super(props);
    this.state = {
      queryParams: {
        useFlag: true, // 仅显示生效
      },
      loading: false,
      columns: [],
      tableData: [{
        key: 1,

      }, {
        key: 2,

      }],
      totalWidth: 0,
      rowID: '',
      rowData: {},
      selectData: {},
      baseInfoFormData: [],
      displayColumns: [],
      displayTotalWidth: 0,
      otherFormData: [],
      displayTableData: [{
        key: 1,

      }, {
        key: 2,

      }],
      displayLoading: false,
      displayRowID: '',
      monitoringColumns: [], // 检测内容表单数据
      monitoringTotalWidth: 0, // 检测内容
      monitoringLoading: false,
      monitoringTableData: []
    };
  };

  componentDidMount() {
    this.getSelectData();
    this.getTableColumns();
    this.getDisplayTableColumns();
    this.getMonitoringColumns();
  };

  componentWillUnmount() {
    this.setState = (state, callback) => { return; }
  };

  // 获取下拉数据
  getSelectData = async () => {
    try {
      let data = {
        params: [{}]
      }
      let res = await React.$asyncPost(this, '04011001', data);
      this.setState({ selectData: res }, () => {
        this.getTableData();
      });
    } catch (error) {
      console.log(error);
    }
  };

  // 获取表头数据
  getTableColumns = async () => {
    try {
      let data = {
        params: [{
          compontName: 'WardInformationSettings',
          type: 'C',
        }]
      }
      let res = await React.$asyncPost(this, '01040073', data);
      let columns = res.result?.C || [];
      if (columns && columns.length > 0) {
        this.setState({
          columns,
          totalWidth: res.totalWidth
        })
      }
      // 表单操作数据
      let baseInfoFormData = res.result?.formData || [];
      if (baseInfoFormData && baseInfoFormData.length > 0) {
        this.setState({ baseInfoFormData });
      }
    } catch (error) {
      console.log(error)
    }
  };

  // 检测方式切换
  handleMonitoringContentTypeChange = e => {
    console.log('e', e)
  };

  // 请求列表数据
  getTableData = async () => {
    try {
      return;
      this.setState({ loading: true })
      let { queryParams } = this.state;
      let data = {
        params: [{
          ...queryParams,
          // Y - 启用; N - 查全部
          useFlag: queryParams.useFlag ? 'Y' : 'N',
        }],
        // pagination: [{
        //   pageSize,
        //   currentPage: page
        // }]
      }
      let res = await React.$asyncPost(this, '123', data);
      let tableData = Util.addKeyValueToDataSource(res.result?.rows || []);
      this.setState({ tableData, total: res.result?.total || 0, loading: false });
    } catch (error) {
      this.setState({ tableData: [], total: 0, loading: false });
    }
  };

  // 修改操作框数据
  handleModifyInputValue = (e, dataIndex) => {
    this.state.queryParams[dataIndex] = e;
    this.setState({}, () => {
      if (dataIndex === 'useFlag') {
        this.handleQuery();
      }
    })
  };

  // 操作行
  onClickRowPublic = (record) => {
    return {
      // 单击行选中
      onClick: () => {
        if (this.state.rowID === '' || (this.state.rowID && (this.state.rowID !== record.key))) {
          this.setState({ rowID: record.key })
        } else {
          this.setState({ rowID: '' })
        }
      }
    }
  };

  // 选中行操作
  setRowClassNamePublic = (record) => {
    return record.key === this.state.rowID ? 'clickRowStyle' : '';
  };

  // 复制
  handleCopy = () => {
    this.copyWardInfoRef && this.copyWardInfoRef.modifyVisible(true);
  };

  handleMove = (direction) => {

  };

  getDisplayTableColumns = async () => {
    try {
      let data = {
        params: [{
          compontName: 'WardInformationDisplaySettings',
          type: 'C',
        }]
      }
      let res = await React.$asyncPost(this, '01040073', data);
      let columns = res.result?.C || [];
      if (columns && columns.length > 0) {
        this.setState({
          displayColumns: columns,
          displayTotalWidth: res.totalWidth
        })
      }
      // 表单操作数据
      let otherFormData = res.result?.formData || [];
      if (otherFormData && otherFormData.length > 0) {
        this.setState({ otherFormData });
      }
    } catch (error) {
      console.log(error)
    }
  };

  // 操作行
  handleDisplayRowClick = (record) => {
    return {
      // 单击行选中
      onClick: () => {
        if (this.state.rowID === '' || (this.state.rowID && (this.state.rowID !== record.key))) {
          this.setState({ rowID: record.key })
        } else {
          this.setState({ rowID: '' })
        }
      }
    }
  };

  // 选中行操作
  handleDisplaySetRowClassName = (record) => {
    return record.key === this.state.displayRowID ? 'clickRowStyle' : '';
  };

  getMonitoringColumns = async () => {
    try {
      let data = {
        params: [{
          compontName: 'WardInformationMonitoring',
          type: 'C',
        }]
      }
      let res = await React.$asyncPost(this, '01040073', data);
      let columns = res.result?.C || [];
      if (columns && columns.length > 0) {
        this.setState({
          monitoringColumns: columns,
          monitoringTotalWidth: res.totalWidth
        })
      }
    } catch (error) {
      console.log(error)
    }
  };

  getOperationObj = (type, data = []) => {
    // 列表操作
    const operationObj = {
      width: 80,
      key: 'operation',
      title: '操作',
      align: 'center',
      render: (text, record, index) => (
        <>
          <Button
            type="link"
            size="small"
            disabled={index === 0}
            style={{ marginRight: '8px' }}
            onClick={(e) => this.handleMove(record, 'up', e)}
          >
            上移
          </Button>
          <Button
            type="link"
            size="small"
            disabled={data?.length - 1 <= index}
            onClick={(e) => this.handleMove(record, 'down', e)}
          >
            下移
          </Button>
        </>
      ),
    };
    return operationObj;
  };

  // 处理许可证数据
  filterFormValues = (formVal, type, key) => {
    let nFormVal = {};
    for (let keys in formVal) {
      if (type === 'add') {
        nFormVal[keys + '_' + key] = formVal[keys];
      } else {
        let currentKey = keys.indexOf('_') > -1 ? keys.split('_')[0] : keys;
        nFormVal[currentKey] = formVal[keys];
      }
    }
    return nFormVal;
  };

  // 保存
  handleSave = async () => {
    try {
      const { rowData } = this.state;
      let data = {
        params: [{

        }]
      }
      let res = await React.$asyncPost(this, '04011002', data);
      message.success(res?.errorMessage || '保存成功');
    } catch (error) {
      console.log(error);
    }
  };

  // 从本科移除
  handleDelete = () => {

  };

  render() {
    const { tabHeight } = this.props;
    const { queryParams, loading, columns, tableData, totalWidth, rowID, rowData, selectData, baseInfoFormData, displayColumns, displayTableData, displayLoading, otherFormData, monitoringColumns, monitoringLoading,
      monitoringTableData
    } = this.state;

    return (
      <div className="ward-information-settings">
        <Row>
          <Col span={10}>
            <div
              style={{ paddingRight: '8px', position: 'relative', height: '100%' }}
            >
              <Card
                size="small"
                bordered={false}
                title={(
                  <div className="card-title-left-img">
                    <img src={iconListVisits} alt="" />
                    病区信息列表
                  </div>
                )}
                extra={(
                  <Checkbox checked={queryParams?.useFlag || false} onChange={(e) => this.handleModifyInputValue(e.target.checked, 'useFlag')}>仅显示生效</Checkbox>
                )}
              >
                <div className="table-body-height">
                  <div style={{ marginBottom: 12 }}>
                    <span className="common-input-label">名称：</span>
                    <Input
                      title="输入内容后可回车检索"
                      placeholder="请输入名称检索"
                      className="common-query-input"
                      style={{ width: '200px' }}
                      value={queryParams?.desc}
                      onChange={(e) => this.handleModifyInputValue(e.target.value, 'desc')}
                      onPressEnter={this.getTableData}
                    />
                    <Button type="primary" style={{ marginRight: 12 }} onClick={this.getTableData}>查询</Button>
                    <Button ghost type="primary" style={{ float: 'right' }} onClick={this.handleCopy}>复制</Button>
                  </div>
                  <PublicTablePagination
                    param={{
                      loading,
                      data: tableData, // 表格数据
                      x: totalWidth, // 表格的宽度
                      y: tabHeight ? tabHeight : store.getState().tableHeight.y + 86,
                      height: tabHeight ? (tabHeight + 50 + 'px') : store.getState().tableHeight.y + 136 + 'px',
                      componentName: 'WardInformationSettings',
                      columns: columns && columns.length > 0 ? [...columns, this.getOperationObj('left', tableData)] : [], // 表头配置
                    }}
                    getColumns={this.getTableColumns}
                    onClickRowPublic={this.onClickRowPublic}
                    setRowClassNamePublic={this.setRowClassNamePublic}
                  />
                </div>
              </Card>
              <div className="common-card-right-split-line" style={{ width: 8 }}></div>
            </div>
          </Col>
          <Col span={14}>
            <Card
              bordered={false}
              size="small"
              title={(
                <div className="card-title-left-img">
                  <img src={iconMessages} alt="" />
                  设置
                </div>
              )}
              extra={(
                rowID && <Button size="small" type="danger" onClick={this.handleDelete}>从本科移除</Button>
              )}
            >
              <div
                style={{
                  height: (tabHeight ? (tabHeight + 92) : store.getState().tableHeight.y + 180) + 'px',
                  overflow: 'auto',
                  padding: '12px'
                }}
                className="scroll-bar-style"
              >
                <DynamicRenderingForm
                  rowData={rowData}
                  selectData={selectData}
                  formData={baseInfoFormData}
                  onRef={ref => this.baseInfoFormRef = ref}
                />
                <Row className="ant-form-item dynamic-rendering-form">
                  <Col span={3} className="ant-form-item-label">
                    <label>显示设置</label>
                  </Col>
                  <Col span={12} className="common-table-empty">
                    <div style={{ minHeight: '82px' }}>
                      <PublicTablePagination
                        param={{
                          loading: displayLoading,
                          data: displayTableData, // 表格数据
                          x: 'none', // 表格的宽度
                          y: 'auto',
                          height: 'auto',
                          componentName: 'WardInformationDisplaySettings',
                          columns: displayColumns ? [...displayColumns, this.getOperationObj('right', displayTableData)] : [], // 表头配置
                        }}
                        getColumns={this.getDisplayTableColumns}
                        onClickRowPublic={this.handleDisplayRowClick}
                        setRowClassNamePublic={this.handleDisplaySetRowClassName}
                      />
                    </div>
                  </Col>
                </Row>
                <DynamicRenderingForm
                  rowData={rowData}
                  selectData={selectData}
                  formData={otherFormData}
                  onRef={ref => this.otherFormRef = ref}
                />
                <Row className="ant-form-item dynamic-rendering-form">
                  <Col span={3} className="ant-form-item-label">
                    <label>监测内容</label>
                  </Col>
                  <Col span={19} className="common-table-empty">
                    <div style={{ minHeight: '82px' }}>
                      <PublicTablePagination
                        param={{
                          loading: monitoringLoading,
                          data: monitoringTableData, // 表格数据
                          x: 'none', // 表格的宽度
                          y: 'auto',
                          height: 'auto',
                          componentName: 'WardInformationMonitoring',
                          columns: monitoringColumns ? [...monitoringColumns] : [], // 表头配置
                        }}
                        getColumns={this.getMonitoringColumns}
                      // onClickRowPublic={this.handleDisplayRowClick}
                      // setRowClassNamePublic={this.handleDisplaySetRowClassName}
                      />
                    </div>
                  </Col>
                </Row>
                <Row style={{ marginTop: '12px' }}>
                  <Col span={3} className="ant-form-item-label"></Col>
                  <Col span={12}>
                    <Button type="primary" onClick={this.handleSave}>保存到本科</Button>
                    <Button style={{ marginLeft: '12px' }}>恢复默认设置</Button>
                  </Col>
                </Row>
              </div>
            </Card>
          </Col>
        </Row>

        {/* 复制配置 */}
        <CopyWardInfoConfig selectData={selectData} onRef={ref => this.copyWardInfoRef = ref} />
      </div>
    )
  }
};

export default WardInformationSettings;